<template>
    <div class="container">
        <div class="form-box">
            <el-form ref="formRef" :rules="rules" :model="form" label-width="110px">
                <el-form-item label="签约公司" prop="companyName">
                    <el-input v-model="form.companyName" disabled></el-input>
                </el-form-item>
                <el-form-item label="签约家政员" prop="remark">
                    <el-input v-model="form.housekeeperName" disabled></el-input>
                </el-form-item>
                <el-form-item label="服务地址" prop="addressId">
                    <el-card>
                        <el-descriptions
                                class="margin-top"
                                :column="2"
                                border>
                            <template #title>
                                <el-button type="primary" @click="handleSelectedAddressBook" :disabled="disabledEdit">
                                    选择
                                </el-button>
                            </template>
                            <el-descriptions-item :width="160">
                                <template #label>
                                    <div class="cell-item">
                                        姓名
                                    </div>
                                </template>
                                {{form.name}}
                            </el-descriptions-item>
                            <el-descriptions-item :width="160">
                                <template #label>
                                    <div class="cell-item">
                                        手机号码
                                    </div>
                                </template>
                                {{form.phone}}
                            </el-descriptions-item>
                            <el-descriptions-item :span="2">
                                <template #label>
                                    <div class="cell-item">
                                        地址
                                    </div>
                                </template>
                                {{form.province}}{{form.city}}{{form.town}}{{form.detail}}
                            </el-descriptions-item>
                        </el-descriptions>
                    </el-card>
                </el-form-item>
                <el-form-item label="服务类型" prop="serviceTypeId">
                    <el-select v-model="form.serviceTypeId" class="m-2" :disabled="disabledEdit">
                        <el-option
                                v-for="item in typeOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="提供住宿" prop="accommodation">
                    <el-radio-group v-model="form.accommodation" :disabled="disabledEdit">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="结算方式" prop="chargeMode">
                    <el-radio-group v-model="form.chargeMode" :disabled="disabledEdit">
                        <el-radio :label="0">时薪</el-radio>
                        <el-radio :label="1">日薪</el-radio>
                        <el-radio :label="2">月薪</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="每期薪资" prop="pay">
                    <el-input-number :min="1" v-model="form.pay" :disabled="disabledEdit"></el-input-number>&nbsp;&nbsp;元
                </el-form-item>
                <el-form-item label="预计服务时间" prop="beginTime">
                    <el-date-picker
                            v-model="serviceTime"
                            type="datetimerange"
                            @change="serviceTimeChange"
                            range-separator="至"
                            start-placeholder="服务开始时间"
                            end-placeholder="服务结束时间"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY/MM/DD HH:mm:ss"
                    />
                </el-form-item>
                <el-form-item label="服务期数" prop="serviceCount">
                    <el-input-number :min="1" v-model="form.serviceCount"></el-input-number>
                </el-form-item>
                <el-form-item label="备注信息" prop="remark">
                    <el-input type="textarea" rows="5" v-model="form.remark"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit(formRef)" :disabled="buttonDisabled">确认签约</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!--地址簿选择-->
        <address-book-selector ref="addressBookDialogRef"
                               @selectedAddressBook="selectedAddressBook"></address-book-selector>
    </div>
</template>

<script setup lang="ts" name="baseform">
    import {nextTick, reactive, ref} from 'vue';
    import {ElMessage, ElLoading} from 'element-plus';
    import type {FormInstance, FormRules} from 'element-plus';
    import AddressCascadeSelector from '../components/AddressCascadeSelector.vue'
    import ImageUploader from '../components/ImageUploader.vue'
    import {
        addDemandApi,
        addHousekeeper,
        createOrderFromDemandApi, createOrderFromHousekeeperApi,
        getDemandApi,
        getHouseKeeperApi,
        getTypeOptions
    } from "../api/index";
    import AddressBookSelector from '../components/AddressBookSelector.vue'
    import {useRoute, useRouter} from "vue-router";

    const rules: FormRules = {
        addressId: [{required: true, message: '请选择地址信息', trigger: 'blur'}],
        pay: [{required: true, message: '请填写预期薪资', trigger: 'blur'}],
        serviceCount: [{required: true, message: '请填写服务期数', trigger: 'blur'}],
        chargeMode: [{required: true, message: '请选择结算方式', trigger: 'blur'}],
        gender: [{required: true, message: '请选择性别需求', trigger: 'blur'}],
        serviceTypeId: [{required: true, message: '请选择服务类型', trigger: 'blur'}],
        accommodation: [{required: true, message: '请选择是否提供住宿', trigger: 'blur'}],
        remark: [{required: true, message: '请填写备注信息', trigger: 'blur'}],
        beginTime: [{required: true, message: '请选择预计服务时间', trigger: 'blur'}],
    };
    const formRef = ref<FormInstance>();
    const form = reactive({
        name: '',
        phone: '',
        province: '',
        city: '',
        town: '',
        detail: '',
        serviceTypeId: null,
        housekeeperName: '',
        companyName: '',
        housekeeperId: null,
        demandId: null,
        serviceCount: null,
        chargeMode: null,
        pay: null,
        accommodation: 0,
        gender: 0,
        remark: '',
        addressId: null,
        beginTime: null,
        endTime: null,
    });
    const typeOptions = ref([]);
    const buttonDisabled = ref(false);
    const disabledEdit = ref(false);
    const route = useRoute();
    const router = useRouter();
    console.log("params", route);
    const params = route.params;
    const orderType = params.type;
    const housekeeperId = params.housekeeperId;
    const demandId = params.demandId;
    if (orderType === 'demand') {
        disabledEdit.value = true;
    }
    const serviceTime = ref({});
    const serviceTimeChange = (e: any) => {
        form.beginTime = e[0];
        form.endTime = e[1];
    };

    const getData = async () => {
        const r1 = await getHouseKeeperApi(housekeeperId);
        const housekeeper = r1.data;
        form.housekeeperId = housekeeperId;
        form.housekeeperName = housekeeper.name;
        form.companyName = housekeeper.companyName;
        if (orderType === 'demand') {
            const r2 = await getDemandApi(demandId);
            const demand = r2.data;
            form.demandId = demandId;
            form.name = demand.name;
            form.phone = demand.phone;
            form.province = demand.province;
            form.city = demand.city;
            form.town = demand.town;
            form.detail = demand.detail;
            form.serviceTypeId = demand.serviceTypeId;
            form.chargeMode = demand.chargeMode;
            form.pay = demand.maxSalary;
            form.accommodation = demand.accommodation;
            form.addressId = 1;
        }
    };


    const getServiceTypeOptions = async () => {
        const res = await getTypeOptions({state: 1});
        if (res) {
            typeOptions.value = res.data;
        }
    };
    const initData = async () => {
        const loading = ElLoading.service({
            lock: true,
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)',
        });
        try {
            await getServiceTypeOptions();
            await getData();
        } finally {
            loading.close();
        }
    };
    if (orderType === 'demand') {
        if (!demandId || !housekeeperId || !orderType) {
            ElMessage.warning("请从指定入口进入签约页面！");
            router.back();
        } else {
            initData();
        }
    } else {
        if (!housekeeperId || !orderType) {
            ElMessage.warning("请从指定入口进入签约页面！");
            router.back();
        } else {
            initData();
        }
    }

    const addressBookDialogRef = ref();
    const handleSelectedAddressBook = () => {
        addressBookDialogRef.value.changeShow(true);
    };
    const selectedAddressBook = (param: any) => {
        console.log("selectedAddressBook", param);
        form.province = param.province;
        form.city = param.city;
        form.town = param.town;
        form.detail = param.detail;
        form.name = param.name;
        form.phone = param.phone;
        form.addressId = param.id;
    };
    // 提交
    const onSubmit = (formEl: FormInstance | undefined) => {
        console.log("onSubmit", form);
        // 表单校验
        if (!formEl) return;
        buttonDisabled.value = true;
        try {
            formEl.validate(async (valid) => {
                if (valid) {
                    let res;
                    if (orderType === 'demand') {
                        res = await createOrderFromDemandApi(form);
                    } else {
                        res = await createOrderFromHousekeeperApi(form);
                    }
                    if (res) {
                        onReset(formEl);
                        ElMessage.success('提交成功，请等待公司接单！');
                        await router.push("/orderForm");
                    }
                } else {
                    return false;
                }
            });
        } finally {
            buttonDisabled.value = false;
        }
    };
    // 重置
    const onReset = (formEl: FormInstance | undefined) => {
        if (!formEl) return;
        formEl.resetFields();
        form.city = '';
        form.town = '';
        form.detail = '';
        form.name = '';
        form.phone = '';
    };
</script>
